package com.klikmee.sms.chat.web.filters;

import java.text.MessageFormat;

import org.apache.log4j.Logger;

import com.klikmee.sms.cef.services.Service;
import com.klikmee.sms.chat.web.dao.SubscriberDAO;
import com.klikmee.sms.services.chat.model.BulkGroupItem;
import com.klikmee.sms.services.chat.model.Question;

/**
 * Message filter that is activated on user unsubscribe request and is used to unsubscribe user from receiving bulk messages sent from chat service.
 * 
 * @author makcro
 * 
 */
public class UnsubscribeFilter extends AbstractFilter {

	/**
	 * Logger instance
	 */
	private Logger logger = Logger.getLogger(UnsubscribeFilter.class);

	/**
	 * Text of the info message to be sent to the user
	 */
	private String unSubscribeInfoText;

	/**
	 * Core id of the service used to unsubscribe user
	 */
	private Long unSubscribeServiceId;

	/**
	 * Core id of the charging used to unsubscribe the user
	 */
	private Long unSubscribeChargingId;

	/**
	 * Instance of subscriber dao used to invalidate sessions
	 */
	private SubscriberDAO subscriberDAO = null;

	/**
	 * Tests question for activation expression and if matched tries to unsubscribe user with the given id, by updating {@link BulkGroupItem#setDisabled(boolean)} property.
	 * 
	 */
	@Override
	public boolean processMessage(Question question) {

		if (question.getQuestion().matches(activationExpression)) {

			logger.info(MessageFormat.format("Successfull match on Unsubscribe filter, core message id = [{0}]", question.getCoreID()));

			int noOfUpdatedRows = subscriberDAO.disableSubscription(question.getFromNumber());

			Long infoCoreId = this.coreAdapter.sendMessage(this.unSubscribeChargingId, this.unSubscribeServiceId, Service.SERVICE_FLAG_SEMANTIC_OK, question.getCoreID(), this.unSubscribeInfoText);

			persistAnswer(question, unSubscribeInfoText, infoCoreId, false);

			// update question so it's not visible to operaters
			question.setVisable(false);
			questionDAO.edit(question);

			logger.info(MessageFormat.format("Disabled subscription for [{0}]", question.getFromNumber()));

			return true;
		}
		return false;
	}

	public void setUnSubscribeInfoText(String unSubscribeInfoText) {
		this.unSubscribeInfoText = unSubscribeInfoText;
	}

	public void setUnSubscribeServiceId(Long unSubscribeServiceId) {
		this.unSubscribeServiceId = unSubscribeServiceId;
	}

	public void setUnSubscribeChargingId(Long unSubscribeChargingId) {
		this.unSubscribeChargingId = unSubscribeChargingId;
	}

	public void setSubscriberDAO(SubscriberDAO subscriberDAO) {
		this.subscriberDAO = subscriberDAO;
	}

}
